// 导入ajax
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { refreshTokenRequest } from '@/api/login'
import { getRefreshToken } from '@/utils/auth'
// 自定义axios
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
import ServerURL from '@/config'
const service = axios.create({
  baseURL: ServerURL + '/genecloud',
  timeout: 600000,
})

//请求拦截
service.interceptors.request.use((config) => {
  if (getToken()) {
    config.headers['Authorization'] = getToken()
  }
  return config
}, error => Promise.reject(error))

// 响应拦截
service.interceptors.response.use(async (response) => {
  if (response.data.code === 200) {
    return response.data
  } else if (response.data.code === 1001 || response.data.code === 1002) {
    //登录状态已过期
    MessageBox.alert('登录状态已过期，请重新登录！', {
      confirmButtonText: '确定',
      callback: () => {
        removeToken()
        location.href = '/login'
      }
    });
  } else if (response.data.code === 401) {
    const message = response.data.message
    MessageBox.alert(message, {
      confirmButtonText: '确定',
      callback: () => {
        removeToken()
        location.href = '/login'
      }
    });
  } else {
    return response.data
  }
}, error => {
  let { message } = error
  if (error.authority) {
    MessageBox.alert(`<p style='color: red'>${message}</p>`, '提示', {
      showClose: false,
      dangerouslyUseHTMLString: true
    })
  } else {
    if (message === 'Network Error') {
      message = '请求后端接口,网络连接异常。'
    } else if (message.includes('timeout')) {
      message = '请求系统接口超时。'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常。'
    }
    MessageBox.alert(message, '提示', {
      confirmButtonText: '确定',
      type: 'error'
    })
  }
  return Promise.reject(error)
})

export default service
